#include "can.h"
#include "gd32f30x.h"
#include "gd32f30x_can.h"

void CanInitFilter() {
  can_filter_parameter_struct can_filter;
  can_struct_para_init(CAN_FILTER_STRUCT, &can_filter);
  /* CAN0 filter number */
  can_filter.filter_number = 0;
  can_filter.filter_mode = CAN_FILTERMODE_MASK;
  can_filter.filter_bits = CAN_FILTERBITS_32BIT;
  can_filter.filter_list_high = 0x0000;
  can_filter.filter_list_low = 0x0000;
  can_filter.filter_mask_high = 0x0000;
  can_filter.filter_mask_low = 0x0000;
  can_filter.filter_fifo_number = CAN_FIFO1;
  can_filter.filter_enable = ENABLE;
  can_filter_init(&can_filter);
}

void CanInitNvic() {
  nvic_irq_enable(CAN0_RX1_IRQn, 0, 0);
  can_interrupt_enable(CAN0, CAN_INT_RFNE1);
}

void CanInit() {
  /* enable CAN clock */
  rcu_periph_clock_enable(RCU_CAN0);
  rcu_periph_clock_enable(RCU_GPIOB);
  rcu_periph_clock_enable(RCU_AF);
  gpio_pin_remap_config(GPIO_CAN_PARTIAL_REMAP, ENABLE); // PB8,PB9需要重隐射
  /* configure CAN0 GPIO */
  gpio_init(GPIOB, GPIO_MODE_IPU, GPIO_OSPEED_MAX, GPIO_PIN_8);
  gpio_init(GPIOB, GPIO_MODE_AF_PP, GPIO_OSPEED_MAX, GPIO_PIN_9);

  can_parameter_struct can_parameter;
  can_struct_para_init(CAN_INIT_STRUCT, &can_parameter);
  /* initialize CAN register */
  can_deinit(CAN0);
  /* initialize CAN */
  can_parameter.time_triggered = DISABLE;
  can_parameter.auto_bus_off_recovery = DISABLE;
  can_parameter.auto_wake_up = DISABLE;
  can_parameter.no_auto_retrans = DISABLE;
  can_parameter.rec_fifo_overwrite = DISABLE;
  can_parameter.trans_fifo_order = DISABLE;
  can_parameter.working_mode = CAN_NORMAL_MODE;
  /* baudrate 500kbps */
  can_parameter.prescaler = 6;
  can_parameter.resync_jump_width = CAN_BT_SJW_1TQ;
  can_parameter.time_segment_1 = CAN_BT_BS1_14TQ;
  can_parameter.time_segment_2 = CAN_BT_BS2_5TQ;
  can_init(CAN0, &can_parameter);
  can_debug_freeze_disable(CAN0);
  CanInitFilter();
  CanInitNvic();
}

can_receive_message_struct can_buf;

void CAN0_RX1_IRQHandler(void) {
  if (can_flag_get(CAN0, CAN_FLAG_RS)) {
    can_message_receive(CAN0, CAN_FIFO1, &can_buf);
    can_flag_clear(CAN0, CAN_FLAG_RS);
  }
};
